'''
Description: 
Author: 月间
Date: 2025-08-16 22:18:46
LastEditTime: 2025-08-24 18:44:36
LastEditors:  
'''
# @Version        : 1.0
# @Update Time    : 2025/8/16 22:18
# @File           : user_manager.py
# @IDE            : PyCharm
# @Desc           : 文件描述信息
from datetime import timedelta
from typing import List

from fastapi import Depends, Request
from fastapi_login import LoginManager

from applications import settings
from applications.core.errors import PermissionException
from applications.models import User


class NotAuthenticatedException(Exception):
    pass


manager = LoginManager(
    settings.SECRET_KEY,
    "/system/passport/login",
    use_cookie=True,
    use_header=False,
    default_expiry=timedelta(hours=2),
    not_authenticated_exception=NotAuthenticatedException,
)


@manager.user_loader()
async def query_user(user_identifier: str):
    user = await User.filter(username=user_identifier).first()
    return user


# 权限认证依赖
def permission_depends(power: str):
    async def check_permission(request: Request, user: User = Depends(manager)):
        if user.enable != 1:
            raise NotAuthenticatedException("用户被禁用")
        if user.username != settings.SUPERADMIN:
            permissions = request.session.get("permissions", [])
            if not permissions or power not in permissions:
                raise PermissionException("无权限")
        return user

    return check_permission


# 角色认证依赖
def role_depends(role: str):
    async def check_role(request: Request, user: User = Depends(manager)):
        if user.enable != 1:
            raise NotAuthenticatedException("用户被禁用")
        if user.username != settings.SUPERADMIN:
            roles = request.session.get("roles", [])
            if not roles or role not in roles:
                raise PermissionException(f"需要{role}角色权限")
        return user

    return check_role
